/*
 * BMessage.cpp
 *
 *  Created on: Oct 2, 2011
 *      Author: eran
 */
#include "BMessage.h"
#include <stdlib.h>
#include <string.h>

BField::BField(BETypeId _rType, BEFieldType _etFieldId)
{
	et_Type = _rType;
	et_FieldId = _etFieldId;
}
BField::~BField()
{

}
BInteger::BInteger(BEFieldType _etFieldId, int _iValue): BField(e_Integer, _etFieldId)
{
	i_Value = _iValue;
	bt_FieldLen = sizeof(int);
}

BInteger::~BInteger()
{

}

UInt BInteger::getStreamBuffer(char * _zStream)
{
	UInt uiRetValue = sizeof(int);
	memcpy(_zStream, &i_Value, uiRetValue);
	return uiRetValue;
}

BMessage::BMessage(BEMessageType _etMessageType, BMessage * _pParent)
{
	for ( UInt ui = 0; ui < _etMessageType; ++ui)
	{
		ap_Fields[ui] = NULL;
	}
	lst_StoredFields.clear();
	ui_MessageLen = 0;
	p_Child = NULL;
	p_Parent = _pParent;
	if ( p_Parent )
	{
		p_Parent->setChild(this);
	}
}

void BMessage::setField(BEFieldType _etFieldType, BField * _pField)
{
	if ( ap_Fields[_etFieldType] )
	{
		removeField(_etFieldType);
	}
	ap_Fields[_etFieldType] = _pField;
	lst_StoredFields.push_back(_pField);
	ui_MessageLen += _pField->getFieldLen();
}

BField * BMessage::getField(BEFieldType _etFieldType)
{
	return ap_Fields[_etFieldType];
}

void BMessage::removeField(BEFieldType _etFieldType)
{
	T_LST_FIELDS::iterator ite = lst_StoredFields.begin();
	while ( ite != lst_StoredFields.end() )
	{
		BEFieldType tid = (*ite)->getFieldId();
		if ( tid == _etFieldType)
		{
			lst_StoredFields.erase(ite);
			ui_MessageLen -= ap_Fields[_etFieldType]->getFieldLen();
			delete ap_Fields[_etFieldType];
			return;
		}
		++ite;
	}
}

UInt BMessage::getStreamBuffer(char * _zStream)
{
	_zStream = new char[ui_MessageLen];
	T_LST_FIELDS::iterator ite = lst_StoredFields.begin();
	while ( ite != lst_StoredFields.end() )
	{
		(*ite)->getStreamBuffer(_zStream);
		++ite;
	}
	return ui_MessageLen;
}

void BMessage::clear()
{
	T_LST_FIELDS::iterator ite = lst_StoredFields.begin();
	while ( ite != lst_StoredFields.end() )
	{
		delete (*ite);
		++ite;
	}
	lst_StoredFields.clear();
}

BMessage::~BMessage()
{
	clear();
}

void BMessage::clearChildren()
{
	if ( p_Child )
	{
		p_Child->clearChildren();
		delete p_Child;
		p_Child = NULL;
	}
	else
	{
		return;
	}
}

